<template>
  <a-modal :width="1200" body-style="padding: 10px 20px" v-model:visible="showEditDialog" :title="currentItem.id ? '编辑申购单' : '创建申购单'" top="8vh" title-align="start" :mask-closable="false" @cancel="closedDialog">
    <a-form ref="formRef" :model="formInfo" :rules="rules">
      <a-row>
        <a-col :span="12">
          <a-form-item field="user.id" label="申购人：" label-col-flex="100px">
            <a-select v-model="formInfo.user" value-key="id" placeholder="" allow-search>
              <a-option v-for="(item, i) in userList" :key="i" :value="item" :label="item.userName" />
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item field="gmtExpectDelivery" label="期望交货日期：" label-col-flex="120px">
            <a-date-picker v-model="formInfo.gmtExpectDelivery" style="width: 100%" />
          </a-form-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :span="12">
          <a-form-item field="warehouse.warehouseCode" label="收货仓：" label-col-flex="100px">
            <a-select v-model="formInfo.warehouse" value-key="warehouseCode" allow-search placeholder="">
              <a-option v-for="(item, i) in warehouseList" :key="i" :value="item" :label="item.warehouseName" />
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="采购服务方式：" label-col-flex="120px">
            <a-select v-model="formInfo.purchaseType" @change="changePurchaseType">
              <a-option value="outer" label="采购公司" />
              <a-option value="inner" label="本公司" />
            </a-select>
            <a-popover>
              <template #content>
                <p>是指提供采购服务的组织。</p>
                <p>采购公司：则是选择一个能提供采购服务的公司作为采购方提供采购跟单服务。</p>
                <p>本公司：则是选择本公司内的一个部门作为采购方提供采购跟单服务。</p>
              </template>
              <icon-question-circle style="margin-left: 5px" />
            </a-popover>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :span="12">
          <a-form-item label="附件：" label-col-flex="100px">
            <div class="flex-wrap">
              <a-tag style="margin-right: 10px; margin-bottom: 10px" v-if="formInfo.attachment" color="arcoblue" @close="formInfo.attachment = ''" closable>
                {{ formInfo.attachment }}
              </a-tag>
              <a-upload action="/" :custom-request="uplaodFile" :show-file-list="false">
                <template #upload-button>
                  <a-button size="mini">
                    <template #icon>
                      <icon-upload />
                    </template>
                    <template #default>上传附件</template>
                  </a-button>
                </template>
              </a-upload>
            </div>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="备注：" label-col-flex="120px">
            <a-textarea v-model="formInfo.remark" placeholder="" allow-clear />
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
    <div class="flex-c-sb" style="margin-bottom: 10px">
      <a-space>
        <a-input-group>
          <a-input size="small" :style="{ width: '260px' }" v-model="searchVal" placeholder="请输入SKU" allow-clear>
            <template #suffix>
              <a-popover position="br" trigger="click" v-model:popup-visible="showPopover" @click="mulValue = searchVal ? searchVal.replace(/,/g, '\n') : ''">
                <icon-more-vertical style="cursor: pointer; margin-left: 5px" />
                <template #content>
                  <a-textarea placeholder="请输入，一行一个" v-model="mulValue" :style="{ width: '200px', height: '200px' }" />
                  <div class="footer flex-c-sb">
                    <a-button class="gray-outline" size="mini" @click="mulValue = ''">清空</a-button>
                    <div>
                      <a-button size="mini" class="gray-outline" @click="showPopover = false">取消</a-button>
                      <a-button type="outline" size="mini" style="margin-left: 5px" @click="addBatch">确认</a-button>
                    </div>
                  </div>
                </template>
              </a-popover>
            </template>
          </a-input>
          <a-button type="primary" size="small" @click="getProductList">添加</a-button>
        </a-input-group>
        <a-button type="primary" size="small" @click="showChooseProductDialog = true">批量选择产品</a-button>
      </a-space>
      <QuotePopover />
    </div>
    <a-table
      class="table-two-line show-border-table"
      ref="tableRef"
      row-key="id"
      :data="purchaseItems"
      :scroll="{
        x: '100%',
        y: 'calc(84vh - 340px)',
      }"
      size="mini"
      :bordered="{ cell: true }"
      :pagination="false"
    >
      <template #columns>
        <a-table-column data-index="img" title="图片" :width="60" fixed="left">
          <template #cell="{ record }">
            <ImgPopover :src="record.productImg">
              <template #con>
                <a-image width="40" height="40" fit="contain" :src="record.productImg" />
              </template>
            </ImgPopover>
          </template>
        </a-table-column>
        <a-table-column data-index="sku" title="SKU" :width="120" fixed="left">
          <template #cell="{ record }">
            <ShowSpuDetailBySku :val="record.sku" :showLimit="false" />
          </template>
        </a-table-column>
        <a-table-column data-index="productSpecs" title="SKU规格" :width="100">
          <template #cell="{ record }">
            <TextLimit :val="getProductSpecs(record)" />
          </template>
        </a-table-column>
        <a-table-column data-index="prop" :width="400">
          <template #title>
            <span>采购参数</span>
            <a-popover content="采购参数默认获取产品属性值，参数项目根据采购场景的属性模版配置而来。">
              <icon-question-circle />
            </a-popover>
          </template>
          <template #cell="{ record, rowIndex }">
            <div class="purchase-props-w">
              <ul class="purchase-props">
                <li v-for="(prop, key) in record.purchaseSpecs" :key="key" :style="`width:${prop.type == 7 || prop.type == 8 ? '100' : '50'}%`">
                  <a-select size="mini" style="width: 100%" v-if="prop.code == 'X-chain'" :trigger-props="{ autoFitPopupMinWidth: true }" v-model="prop.purchaseValue" @search="getChainList" :filter-option="false" allow-clear allow-search :placeholder="prop.name" @change="changeProp(prop, rowIndex)">
                    <a-option v-for="(propVal, j) in chainList" :key="j" :value="propVal.skuName" :label="propVal.skuName" />
                  </a-select>
                  <a-select size="mini" style="width: 100%" v-else-if="prop.type == 1" :trigger-props="{ autoFitPopupMinWidth: true }" v-model="prop.purchaseValue" allow-clear allow-search :placeholder="prop.name" @change="changeProp(prop, rowIndex)">
                    <a-option v-for="(propVal, j) in prop.propValueList" :key="j" :value="propVal.propValue" :label="propVal.propValue" />
                  </a-select>
                  <a-select size="mini" style="width: 100%" v-else-if="prop.type == 2" :trigger-props="{ autoFitPopupMinWidth: true }" multiple :max-tag-count="1" v-model="prop.purchaseValue" allow-search allow-clear @change="changeProp(prop, rowIndex)" :placeholder="prop.name">
                    <a-option v-for="(propVal, j) in prop.propValueList" :key="j" :value="propVal.propValue" :label="propVal.propValue" />
                  </a-select>
                  <a-select size="mini" style="width: 100%" v-else-if="prop.type == 3" :trigger-props="{ autoFitPopupMinWidth: true }" v-model="prop.purchaseValue" allow-clear allow-search :placeholder="prop.name" @change="changeProp(prop, rowIndex)">
                    <a-option value="true" label="是" />
                    <a-option value="false" label="否" />
                  </a-select>
                  <a-input size="mini" v-else-if="prop.type == 4" v-model="prop.purchaseValue" allow-clear :placeholder="prop.name" />
                  <a-input-number size="mini" v-else-if="prop.type == 5 || prop.type == 6" v-model="prop.purchaseValue" allow-clear :placeholder="prop.name" :min="0" hide-button>
                    <template #suffix>
                      {{ prop.unit }}
                    </template>
                  </a-input-number>
                  <div v-else-if="prop.type == 7">
                    <a-input size="mini" v-model="prop.purchaseValue[0]" style="width: 33.33%" allow-clear :placeholder="prop.name" hide-button>
                      <template #suffix>
                        {{ prop.unit }}
                      </template>
                    </a-input>
                    <a-input size="mini" v-model="prop.purchaseValue[1]" style="width: 33.33%" allow-clear :placeholder="prop.name" hide-button>
                      <template #suffix>
                        {{ prop.unit }}
                      </template>
                    </a-input>
                    <a-input size="mini" v-model="prop.purchaseValue[2]" style="width: 33.33%" allow-clear :placeholder="prop.name" hide-button>
                      <template #suffix>
                        {{ prop.unit }}
                      </template>
                    </a-input>
                  </div>
                  <div v-else-if="prop.type == 8">
                    <a-input size="mini" v-model="prop.purchaseValue[0]" style="width: 50%" :placeholder="prop.name" allow-clear hide-button>
                      <template #suffix>
                        {{ prop.unit }}
                      </template>
                    </a-input>
                    <a-input size="mini" v-model="prop.purchaseValue[1]" style="width: 50%" :placeholder="prop.name" allow-clear hide-button>
                      <template #suffix>
                        {{ prop.unit }}
                      </template>
                    </a-input>
                  </div>
                </li>
              </ul>
              <div>
                <icon-double-down v-if="rowIndex != purchaseItems.length - 1" class="edit-icon" @click="setGlobalPurchaseSpecs(record, rowIndex)" />
                <a-popover position="bottom" trigger="click">
                  <template #content>
                    <p class="props-title">采购参数属性配置</p>
                    <a-scrollbar style="height: 300px; overflow: auto">
                      <ul class="props-list">
                        <li class="flex-c-sb" v-for="(item, i) in allProps" :key="i" @click="chooseProp(item, record, rowIndex)">
                          <span>{{ item.name }}</span>
                          <span v-if="record.purchaseSpecs && record.purchaseSpecs[item.code]"><icon-eye /></span>
                          <span v-else><icon-eye-invisible /></span>
                        </li>
                      </ul>
                    </a-scrollbar>
                  </template>
                  <p><icon-down-circle class="edit-icon" /></p>
                </a-popover>
              </div>
            </div>
          </template>
        </a-table-column>
        <a-table-column data-index="remark" title="备注" :width="140">
          <template #cell="{ record, rowIndex }">
            <div class="cell flex-c" style="width: 132px">
              <a-input v-model="record.remark" style="width: 90px" placeholder="" />
              <icon-double-down v-if="rowIndex != purchaseItems.length - 1" class="edit-icon" @click="setGlobal(record, 'remark', rowIndex)" />
            </div>
          </template>
        </a-table-column>
        <a-table-column title="采购方" :width="180">
          <template #title>
            <span class="warningColor">*</span>
            <span>采购方</span>
            <a-popover>
              <template #content>
                <p style="width: 400px">如果采购服务方式=采购公司：则择一个能提供采购服务的公司作为采购方提供采购跟单服务。</p>
                <p style="width: 400px">如果采购服务方式=本公司：则选择本公司内的一个部门作为采购方提供采购跟单服务。</p>
              </template>
              <icon-question-circle />
            </a-popover>
          </template>
          <template #cell="{ record, rowIndex }">
            <div class="cell flex-c">
              <a-cascader v-if="formInfo.purchaseType == 'inner'" value-key="purchaseOrgId" allow-search v-model="record.purchaseOrgInfo" allow-clear check-strictly :options="deptList" :fieldNames="{ label: 'purchaseOrgName' }" style="width: 140px" />
              <a-select v-else v-model="record.purchaseOrgInfo" placeholder="" value-key="purchaseOrgId" style="width: 140px" allow-search>
                <a-option v-for="(item, i) in purchaseCompanyList" :key="i" :value="item" :label="item.purchaseOrgName" />
              </a-select>
              <icon-double-down v-if="rowIndex != purchaseItems.length - 1" class="edit-icon" @click="setGlobal(record, 'purchaseOrgInfo', rowIndex)" />
            </div>
          </template>
        </a-table-column>
        <a-table-column :width="120">
          <template #title>
            <p>
              <span class="warningColor">*</span>
              <span>申购数量</span>
            </p>
          </template>
          <template #cell="{ record, rowIndex }">
            <a-input-number v-model="record.planAmt" style="width: 80px" placeholder="" />
            <icon-double-down v-if="rowIndex != purchaseItems.length - 1" class="edit-icon" @click="setGlobal(record, 'planAmt', rowIndex)" />
          </template>
        </a-table-column>
        <a-table-column title="材质单价" :width="130">
          <template #title>
            <span class="warningColor">*</span>
            <span>材质单价</span>
            <a-popover>
              <template #content>
                <p style="width: 400px">按材质重量定价的产品，请务必填写材质单价。默认获取当前时间最新的材质报价数据，未获取到可能是采购参数上没有材质属性。不需要按材质价格的则可以填写0。</p>
              </template>
              <icon-question-circle />
            </a-popover>
          </template>
          <template #cell="{ record, rowIndex }">
            <div class="flex-c">
              <a-input-number v-model="record.materialPrice" style="width: 90px" :min="0" :max="100" :precision="2" placeholder="" />
              <icon-double-down v-if="rowIndex != purchaseItems.length - 1" class="edit-icon" @click="setGlobal(record, 'materialPrice', rowIndex)" />
            </div>
          </template>
        </a-table-column>
        <a-table-column title="单件工费" :width="270">
          <template #title>
            <span class="warningColor">*</span>
            <span>单件工费</span>
            <a-popover>
              <template #content>
                <p>工费：这里的工费单价是指采购服务方提供采购服务的工费</p>
                <p>固定值：固定单价默认获取工费报价表，或者从最近一次申购单获取。</p>
                <p>产品单价比例：根据入库单上的产品单价按百分比计算工费</p>
              </template>
              <icon-question-circle />
            </a-popover>
          </template>
          <template #cell="{ record, rowIndex }">
            <div class="flex-c">
              <a-select v-model="record.laborPriceType" style="width: 130px">
                <a-option :value="1">固定值</a-option>
                <a-option :value="2">产品单价比例</a-option>
              </a-select>
              <a-input-number :min="0" v-model="record.singleLaborCosts" style="width: 90px" placeholder="" :precision="2" />
              <span v-if="record.laborPriceType === 2">%</span>
              <icon-double-down v-if="rowIndex != purchaseItems.length - 1" class="edit-icon" @click="setGlobalLaborCost(record, rowIndex)" />
            </div>
          </template>
        </a-table-column>
        <a-table-column title="是否加急" :width="100">
          <template #cell="{ rowIndex, record }">
            <a-space>
              <a-switch v-model="record.urgent" checked-text="开" unchecked-text="关" />
              <icon-double-down v-if="rowIndex != purchaseItems.length - 1" class="edit-icon" @click="setGlobal(record, 'urgent', rowIndex)" />
            </a-space>
          </template>
        </a-table-column>
        <a-table-column title="操作" :width="60" fixed="right">
          <template #cell="{ rowIndex }">
            <a-popconfirm v-if="purchaseItems.length > 1" content="确定是否移除?" @ok="purchaseItems.splice(rowIndex, 1)" type="error">
              <a-button type="text">移除</a-button>
            </a-popconfirm>
          </template>
        </a-table-column>
      </template>
    </a-table>
    <template #footer>
      <a-space>
        <a-button size="small" class="gray-outline" @click="closedDialog">取消</a-button>
        <a-button v-if="$authPass('procurement.plan.submit')" size="small" type="primary" @click="submitData(10)" :disabled="submitLoading">保存并提交审核</a-button>
        <a-button size="small" type="primary" @click="submitData(currentItem.status || 1)" :disabled="submitLoading">保存</a-button>
      </a-space>
    </template>
  </a-modal>
  <!-- 选择产品 -->
  <ChooseProduct v-if="showChooseProductDialog" title="添加采购产品" :needCount="false" :isShow="showChooseProductDialog" :multiple="true" @closed="showChooseProductDialog = false" @success="chooseProduct" />
</template>
<script lang="ts" setup>
  import { ref, onMounted, PropType } from 'vue'
  import useUserStore from '@/store/modules/user'
  import { upload } from '@/api/base'
  import { Message } from '@arco-design/web-vue'
  import QuotePopover from './quotePopover.vue'
  import { createPurchasePlan, updatePurchasePlan, findErpPurchaseQuoteCost, findLatestPlanItemList } from '@/api/purchaseApplication'
  import { parseJson } from '@/utils'
  import useBaseDataStore from '@/store/modules/base-data'
  import ChooseProduct from '@/components/ChooseProduct.vue'
  import { skuPageRelatedForCompanyVer, getRelatedList, pageFitting, getPropertyTemplateList } from '@/api/product'
  import { cloneDeep } from 'lodash-es'
  import { findMaterialQuotePage } from '@/api/system'

  onMounted(() => {
    getAllProps()
    getPurchaseProps()
    getDeptList()
    getQuoteList()
    getChainList()
    if (props.currentItem.id) {
      getOrderDetail()
    } else {
      setDefaultData()
    }
    purchaseCompanyList.value = props.companyList.filter((el: any) => el.outPurchase)
  })
  const emit = defineEmits(['closed', 'success'])
  const props = defineProps({
    isShow: {
      type: Boolean,
      default: false,
    },
    userList: {
      type: Array as PropType<Array<any>>,
      default: () => [],
    },
    companyList: {
      type: Array as PropType<Array<any>>,
      default: () => [],
    },
    warehouseList: {
      type: Array as PropType<Array<any>>,
      default: () => [],
    },
    currentItem: {
      type: Object,
      default: () => {},
    },
  })
  const purchaseCompanyList = ref<Array<any>>([])
  const rules = ref({
    'warehouse.warehouseCode': [{ required: true, message: '请选择目的仓库' }],
    'user.id': [{ required: true, message: '请选择采购员' }],
    gmtExpectDelivery: [{ required: true, message: '请选择期望交货日期' }],
  })
  const userStore = useUserStore()
  const showEditDialog = ref(props.isShow)
  const formInfo = ref<any>({})
  const purchaseItems = ref<Array<any>>([])
  const submitLoading = ref(false)
  const showChooseProductDialog = ref(false)
  const formRef = ref()
  const useBaseData = useBaseDataStore()
  const searchVal = ref()
  const mulValue = ref()
  const showPopover = ref(false)
  const allProps = ref<Array<any>>([])
  const quoteList = ref<Array<any>>([])
  let quoteMap: any = {}
  const deptList = ref<Array<any>>([])
  let skuPropsMap: any = {}
  let purchasePropsMap: any = {}
  const chainList = ref<Array<any>>([])
  const chainCatId = import.meta.env.VITE_CHAIN_CATEGORY_ID

  // 获取配链列表
  async function getChainList(val?: string) {
    const params: any = {
      keyword: val,
      keywordType: 'skuName',
      searchType: 'fuzzy',
      needCount: false,
      categoryId: chainCatId,
      pageNum: 1,
      pageSize: 50,
    }
    const res: any = await pageFitting(params)
    chainList.value = res?.data?.records || []
  }

  // 获取部门列表
  async function getDeptList() {
    await useBaseData.getDeptList()
    deptList.value = cloneDeep(useBaseData.deptList)
    setDeptVal(deptList.value)
  }
  function setDeptVal(list: Array<any>) {
    list.forEach((el: any) => {
      el.purchaseOrgName = el.deptName
      el.purchaseOrgId = el.id
      el.value = {
        purchaseOrgName: el.deptName,
        purchaseOrgId: el.id,
      }
      if (el.children?.length) {
        setDeptVal(el.children)
      } else {
        delete el.children
      }
    })
  }
  // 获取报价列表
  async function getQuoteList() {
    let params = {
      pageNum: 1,
      pageSize: 500,
      display: true,
    }
    const res: any = await findMaterialQuotePage(params)
    quoteList.value = res?.data?.records || []
    quoteList.value.forEach((el: any) => {
      quoteMap[el.productName] = el
    })
  }

  // 获取详情
  async function getOrderDetail() {
    let _detail = props.currentItem
    formInfo.value = {
      gmtExpectDelivery: _detail.gmtExpectDelivery,
      purchaseType: _detail.purchaseType,
      attachment: _detail.attachment,
      remark: _detail.remark,
      id: _detail.id,
      status: _detail.status,
    }
    if (_detail.warehouseCode) {
      formInfo.value.warehouse = {
        warehouseCode: _detail.warehouseCode,
        warehouseName: _detail.warehouseName,
      }
    }
    if (_detail.salesmanId) {
      formInfo.value.user = {
        id: _detail.salesmanId,
        userName: _detail.salesmanName,
      }
    }
    // purchaseItems.value = JSON.parse(JSON.stringify(_detail.billItems))
    purchaseItems.value = _detail.billItems.map((el: any) => {
      // let _params:any = {}
      // let arr = ['asin','billId','brandId','brandName','cateId','cateName','companyId','companyName','fnsku','id','labels','laborAmount','laborPrice','laborPriceType','laborRate','marketplaceId','materialAmount','materialPrice']
      if (el.purchaseOrgId) {
        el.purchaseOrgInfo = {
          purchaseOrgId: el.purchaseOrgId,
          purchaseOrgName: el.purchaseOrgName,
        }
      }
      el.purchaseSpecs = parseJson(el.purchaseSpecs, {}) || {}
      el.singleLaborCosts = el.laborPriceType === 1 ? el.laborPrice : el.laborRate
      return el
    })
  }
  // 单个切换材质
  function changeProp(prop: any, index: number) {
    // 切换了材质需要更换材质报价
    if (prop.name == '材质') {
      purchaseItems.value[index].materialPrice = quoteMap[prop.purchaseValue]?.quotePrice
    }
  }
  // 批量同步属性数据

  // 获取所有的属性列表
  async function getAllProps() {
    const res = await getRelatedList({
      pageNum: 1,
      pageSize: 1000,
    })
    allProps.value = res?.data?.records || []
  }
  // 获取采购场景的属性模板  一个类目加采购场景为一条数据
  async function getPurchaseProps() {
    purchasePropsMap = {}
    const res = await getPropertyTemplateList({
      pageNum: 1,
      pageSize: 1000,
      scenes: 'purchase',
    })
    let _list = res?.data?.records || []
    _list.forEach((item: any) => {
      let propItems = item.itemList.map((propEl: any) => propEl.prop)
      item.categoryList.forEach((el: any) => {
        purchasePropsMap[el.productCatgoryId] = propItems
      })
    })
  }

  // 点击增加或隐藏属性
  function chooseProp(prop: any, item: any, index: number) {
    item.purchaseSpecs = item.purchaseSpecs || {}
    if (item.purchaseSpecs?.[prop.code]) {
      delete item.purchaseSpecs[prop.code]
    } else {
      let purchaseValue = getAddPropVal(prop, item.sku)
      item.purchaseSpecs[prop.code] = {
        ...prop,
        purchaseValue: purchaseValue,
      }
      changeProp(item.purchaseSpecs[prop.code], index)
    }
  }
  function getAddPropVal(prop: any, sku: string) {
    let purchaseValue: any
    // 获取产品的属性值
    let productProp = skuPropsMap?.[sku]?.[prop.code] || {}
    switch (prop.type) {
      case 1:
        purchaseValue = productProp.valueStr || null
        break
      case 2:
        purchaseValue = productProp.valueStrList || []
        break
      case 3:
        purchaseValue = productProp.valueBoolean || null
        break
      case 4:
        purchaseValue = productProp.valueStr || null
        break
      case 5:
        purchaseValue = productProp.valueNumber || null
        break
      case 6:
        purchaseValue = productProp.valueBigDecimal || null
        break
      case 7:
        let strs = productProp.valueStrList || []
        purchaseValue = [strs[0] || '', strs[1] || '', strs[2] || '']
      case 8:
        let strs2 = productProp.valueStrList || []
        purchaseValue = [strs2[0] || '', strs2[1] || '']
        break
      default:
        break
    }
    return purchaseValue
  }
  // 显示sku规格
  function getProductSpecs(item: any) {
    let productSpecs = item.productSpecs ? parseJson(item.productSpecs, []) : []
    return productSpecs.map((el: any) => el.valueCn)?.join('*') || '--'
  }

  // 添加初始化数据
  function setDefaultData() {
    let defaultUser = {
      id: userStore.userId,
      userName: userStore.userName,
    }
    formInfo.value.user = { ...defaultUser }
    formInfo.value.purchaseType = 'outer'
  }
  function addBatch() {
    searchVal.value = mulValue.value?.split('\n')?.join(',')
    showPopover.value = false
  }

  // 上传附件
  async function uplaodFile(options: any) {
    let { fileItem } = options
    let formData = new FormData()
    formData.append('file', fileItem.file)
    const res: any = await upload(formData)
    if (res?.data?.publicUrl) {
      formInfo.value.attachment = res.data.publicUrl
    }
  }
  //设置全局
  function setGlobal(item: any, key: string, rowIndex: number) {
    const newVal = item[key]
    purchaseItems.value.forEach((el: any, index: number) => {
      if (index > rowIndex) {
        el[key] = typeof newVal == 'object' ? cloneDeep(newVal) : newVal
      }
    })
  }
  //设置属性全局
  function setGlobalPurchaseSpecs(item: any, rowIndex: number) {
    const newVal = item.purchaseSpecs
    purchaseItems.value.forEach((el: any, index: number) => {
      if (index > rowIndex) {
        el.purchaseSpecs = cloneDeep(newVal)
        //更新默认报价
        Object.values(el.purchaseSpecs).forEach((prop: any) => {
          if (prop.name == '材质') {
            changeProp(prop, index)
          }
        })
      }
    })
  }
  //全局设置单件工工费
  function setGlobalLaborCost(item: any, rowIndex: number) {
    setGlobal(item, 'laborPriceType', rowIndex)
    setGlobal(item, 'singleLaborCosts', rowIndex)
  }
  // 添加产品的信息
  function setItemInfoByProduct(item: any) {
    let obj: any = {
      productId: item.id,
      productImg: item?.productPicList?.[0]?.url,
      productName: item.skuName,
      productSpecs: item.specValueList ? JSON.stringify(item.specValueList) : null,
      productRemark: item.remark,
      sku: item.sku,
      spu: item.spu,
      brandId: item?.brand?.id,
      brandName: item?.brand?.name,
      cateId: item.category?.id,
      cateName: item.category?.name,
      urgent: false,
      remark: item.remark,
      laborPriceType: 1,
      purchaseSpecs: {},
      purchaseDept: item.purchaseDeptList?.[0],
    }
    // 有采购模板的默认采购模板
    let purchaseProps = purchasePropsMap[obj.cateId]
    if (purchaseProps?.length) {
      purchaseProps.forEach((prop: any) => {
        let purchaseValue = getAddPropVal(prop, obj.sku)
        obj.purchaseSpecs[prop.code] = {
          ...prop,
          purchaseValue: purchaseValue,
        }
      })
    }
    // 设置默认材质单价，取报价里相同材质的价格
    let material = Object.values(obj.purchaseSpecs)?.find((el: any) => el.name == '材质')?.purchaseValue
    if (material) {
      obj.materialPrice = quoteMap[material]?.quotePrice
    }
    return obj
  }
  // 添加产品
  async function chooseProduct(list: Array<any>) {
    // 不重复添加相同SKU
    let addList = list.filter((item: any) => !purchaseItems.value.some((el: any) => item.sku == el.sku))
    if (!addList?.length) return
    let skus: Array<string> = []
    addList.forEach((el: any) => {
      skus.push(el.sku)
      skuPropsMap[el.sku] = {}
      el.propList?.forEach((prop: any) => {
        skuPropsMap[el.sku][prop.code] = prop
      })
      purchaseItems.value.push(setItemInfoByProduct(el))
    })
    await getErpPurchaseQuoteCost(skus)
    const planItems = await getLatestPlanItemList(skus)
    setDefaultCost(planItems, skus)
    setDefaultPurchaseOrg(planItems, skus)
  }
  // 默认工费
  function setDefaultCost(list: Array<any>, skus: Array<string>) {
    let planItemMapBysku: any = {}
    list.forEach((el: any) => {
      planItemMapBysku[el.sku] = el
    })
    purchaseItems.value.forEach((el: any) => {
      // 新增的产品需要取默认值
      if (skus.includes(el.sku)) {
        // 工费优先取采购报价的金额，没有则取最近申购单上的工费
        let planItemInfo = planItemMapBysku[el.sku] || {}
        if (!el.singleLaborCosts) {
          el.laborPriceType = planItemInfo.laborPriceType || 1
          el.singleLaborCosts = planItemInfo.laborPrice
        }
      }
    })
  }
  // 默认采购方
  function setDefaultPurchaseOrg(list: Array<any>, skus: Array<string>) {
    let planItemMap: any = {}
    list.forEach((el: any) => {
      let key = el.sku + el.purchaseType
      planItemMap[key] = el
    })
    purchaseItems.value.forEach((el: any) => {
      // 新增的产品默认取最近一次申购单上的采购方， 如果获取不到则取产品上的持有人信息的采购部信息。
      if (skus.includes(el.sku)) {
        let planItePurchaseOrg = planItemMap[el.sku + formInfo.value.purchaseType] || {}
        if (planItePurchaseOrg.purchaseOrgId) {
          el.purchaseOrgInfo = {
            purchaseOrgId: planItePurchaseOrg.purchaseOrgId,
            purchaseOrgName: planItePurchaseOrg.purchaseOrgName,
          }
        } else if (el.purchaseDept?.id) {
          // 采购方式-内部部门，取部门ID和name
          if (formInfo.value.purchaseType === 'inner') {
            el.purchaseOrgInfo = {
              purchaseOrgId: el.purchaseDept.id,
              purchaseOrgName: el.purchaseDept.name,
            }
          } else if (formInfo.value.purchaseType === 'outer' && el.purchaseDept.companyId) {
            let purchaseOrgId = el.purchaseDept.companyId
            let purchaseOrgName = purchaseCompanyList.value.find((company: any) => company.purchaseOrgId == purchaseOrgId)?.purchaseOrgName
            el.purchaseOrgInfo = {
              purchaseOrgId: purchaseOrgId,
              purchaseOrgName: purchaseOrgName,
            }
          }
        }
      }
    })
  }
  // 获取工费报价
  async function getErpPurchaseQuoteCost(skus: Array<string>) {
    const res: any = await findErpPurchaseQuoteCost({ skus })
    let erpCostMap: any = {}
    let list = res?.data || []
    list.forEach((el: any) => {
      erpCostMap[el.productSku] = el
    })
    purchaseItems.value.forEach((el: any) => {
      // 工费优先取采购报价的金额
      el.singleLaborCosts = valIsNull(el.singleLaborCosts) ? erpCostMap[el.sku]?.singleLaborAmount : el.singleLaborCosts
    })
  }
  // 查询最新申购单明细,取默认的申购公司和申购工费
  async function getLatestPlanItemList(skus: Array<string>) {
    const res: any = await findLatestPlanItemList({ skus: skus.join(',') })
    return res?.data || []
  }
  function valIsNull(str: string) {
    return str === '' || str === null || str === undefined
  }
  // 输入sku直接添加产品
  async function getProductList() {
    if (!searchVal.value) return
    const res: any = await skuPageRelatedForCompanyVer({
      pageSize: 100,
      pageNum: 1,
      searchType: 'exact',
      keywordType: 'sku',
      keyword: searchVal.value,
    })
    let list = res?.data?.records || []
    chooseProduct(list)
  }

  // 关闭
  function closedDialog() {
    showEditDialog.value = false
    emit('closed')
  }
  // 切换采购方类型
  async function changePurchaseType() {
    let skus: Array<any> = []
    purchaseItems.value.forEach((el: any) => {
      el.purchaseOrgInfo = null
      skus.push(el.sku)
    })
    const planItems = await getLatestPlanItemList(skus)
    setDefaultPurchaseOrg(planItems, skus)
  }

  // 校验
  async function validInfo() {
    let valid = await formRef.value.validate((valid: any) => {
      return valid
    })
    if (valid) return false
    if (!purchaseItems.value.length) {
      Message.error('请最少增加一个产品')
      return false
    }
    for (let el of purchaseItems.value) {
      if (!el.purchaseOrgInfo?.purchaseOrgId) {
        Message.error('申购方必选')
        return false
      }
      if (!el.planAmt) {
        Message.error('申购数量必填')
        return false
      }
      if (!(el.materialPrice || el.materialPrice === 0)) {
        Message.error('材质单价必填')
        return false
      }

      if (!(el.singleLaborCosts || el.singleLaborCosts === 0)) {
        Message.error('单件工费必填')
        return false
      }
    }
    return true
  }
  function saveItemData() {
    let list = JSON.parse(JSON.stringify(purchaseItems.value))
    list.forEach((el: any) => {
      el.purchaseOrgId = el.purchaseOrgInfo?.purchaseOrgId
      el.purchaseOrgName = el.purchaseOrgInfo?.purchaseOrgName

      el.purchaseSpecs = JSON.stringify(el.purchaseSpecs || {})
      if (el.laborPriceType === 1) {
        el.laborPrice = el.singleLaborCosts
        el.laborRate = null
      } else {
        el.laborPrice = null
        el.laborRate = el.singleLaborCosts
      }
      delete el.singleLaborCosts
      delete el.purchaseOrgInfo
      delete el.purchaseType
      delete el.purchaseDept
    })
    return list
  }
  // 保存信息
  async function submitData(status: number) {
    let valid = await validInfo()
    if (!valid) return false
    let formVal = cloneDeep(formInfo.value)
    formVal.salesmanId = formVal.user?.id
    formVal.salesmanName = formVal.user?.userName
    formVal.warehouseCode = formVal.warehouse?.warehouseCode
    formVal.warehouseName = formVal.warehouse?.warehouseName
    delete formVal.user
    delete formVal.warehouse
    let params: any = {
      ...formVal,

      billItems: saveItemData(),
      status: status,
    }
    submitLoading.value = true
    let res: any
    if (!props.currentItem.id) {
      res = await createPurchasePlan(params)
    } else {
      params.id = formInfo.value.id
      res = await updatePurchasePlan(params)
    }
    submitLoading.value = false
    if (!res) return false
    Message.success('保存成功')
    emit('success')
    closedDialog()
  }
</script>
<style lang="less" scoped>
  .arco-form-item {
    margin-bottom: 10px;
  }

  .edit-icon {
    font-size: 16px;
    margin-left: 5px;
    cursor: pointer;
  }
  .price-type {
    font-size: 12px;
    transform: scale(0.82);
    position: relative;
    left: -4px;
  }
  :deep(td.shopInfo .arco-table-cell) {
    padding: 0 !important;
  }
  .shop-list {
    display: flex;
    border-bottom: 1px solid var(--color-neutral-3);
    &:last-child {
      border-bottom: none;
    }
    .item {
      height: 56px;
      display: flex;
      align-items: center;
      padding: 0 5px;
      border-right: 1px solid var(--color-neutral-3);
      &:last-child {
        border-right: none;
      }
    }
  }
  .props-list {
    width: 200px;
    li {
      padding-right: 10px;
      margin-bottom: 5px;
    }
  }
  .props-title {
    margin-bottom: 5px;
  }
  .purchase-props {
    display: flex;
    flex-wrap: wrap;
    flex: 1;
    li {
      width: 50%;
      padding-right: 5px;
      margin-top: 5px;
    }
  }
  .purchase-props-w {
    display: flex;
    justify-content: space-between;
  }
</style>
